package com.peanutplan.blog.controller.admin;

import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.peanutplan.blog.controller.BaseController;
import com.peanutplan.blog.dao.IndexMenuMapper;
import com.peanutplan.blog.exception.TipException;
import com.peanutplan.blog.model.bo.RestResponseBo;
import com.peanutplan.blog.model.vo.EsHotWord;
import com.peanutplan.blog.model.vo.IndexMenu;

import tk.mybatis.mapper.entity.Example;

/**
 * <p>Title: IndexMenusController</p>
 * <p>Description: </p>
 * @author motisy
 * @date 2020年3月11日
 */
@Controller
@RequestMapping("admin/indexMenu")
public class IndexMenuController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexMenuController.class);

    @Resource
    private IndexMenuMapper indexMenuMapper;

    @PostMapping(value = "save")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo<?> save(IndexMenu indexMenu) {
        try {
        	if(indexMenu.getName().equals("导航")) {
        		throw new TipException("【导航】为默认菜单，不能重复添加！");
        	}
        	if(indexMenu.getName().equals("首页")) {
        		throw new TipException("【首页】为默认菜单，不能重复添加！");
        	}
        	if(StringUtils.isBlank(indexMenu.getName())) {
        		throw new TipException("名称不能为空");
        	}
        	if(StringUtils.isBlank(indexMenu.getUrl())) {
        		throw new TipException("链接不能为空");
        	}
        	if(indexMenu.getIndex()==null) {
        		throw new TipException("序号名称不能为空");
        	}
        	Example example = new Example(IndexMenu.class);
        	example.createCriteria().andEqualTo("index", indexMenu.getIndex());
        	long count = indexMenuMapper.selectCountByExample(example);
        	if(count>0) {
        		return RestResponseBo.fail("序号请不要重复添加！");
        	} 
        	if(StringUtils.isBlank(indexMenu.getType())) {
        		indexMenu.setType(IndexMenu.DEFAULT_MENU);
        	}
        	if(indexMenu.getType().equals(IndexMenu.CATEGORY_MENU)) {
        		indexMenu.setUrl("category");
        	}
        	if(indexMenu.getType().equals(IndexMenu.CATEGORY_MENU)) {
        		indexMenu.setUrl("option");
        	}
        	indexMenu.setStatus(1);
        	indexMenuMapper.insert(indexMenu);
        } catch (Exception e) {
            String msg = "保存失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }
    
    /**
     * 评论列表
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping(value = "")
    public String index(HttpServletRequest request) {
        List<IndexMenu> list = indexMenuMapper.selectAll();
        list.sort(Comparator.comparing(IndexMenu::getIndex).thenComparing(IndexMenu::getName));
        request.setAttribute("menus", list);
        return "admin/indexMenus_list";
    }

    /**
     * 删除一条评论
     * @param coid
     * @return
     */
    @PostMapping(value = "delete")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo<?> delete(@RequestParam Long id) {
        try {
            indexMenuMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            String msg = "删除失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }
    
    /**
     * 删除一条评论
     * @param coid
     * @return
     */
    @PostMapping(value = "up")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo<?> up(@RequestParam Long id) {
        try {
        	IndexMenu m = indexMenuMapper.selectByPrimaryKey(id);
        	
        	Example example = new Example(IndexMenu.class);
        	example.createCriteria().andLessThanOrEqualTo("index", m.getIndex()).andNotEqualTo("id", m.getId());
        	example.setOrderByClause("index_ desc");
        	List<IndexMenu> list = indexMenuMapper.selectByExample(example);
        	IndexMenu pre = null;
        	if(list!=null && list.size()>0) {
        		pre = list.get(0);
        		if(pre.getIndex()<m.getIndex()) {
        			int i = pre.getIndex();
        			pre.setIndex(m.getIndex());
        			m.setIndex(i);
        			indexMenuMapper.updateByPrimaryKey(pre);
        			indexMenuMapper.updateByPrimaryKey(m);
        		}else {
        			//相等了
        			Example example2 = new Example(IndexMenu.class);
                	example2.createCriteria().andGreaterThanOrEqualTo("index", m.getIndex()).andNotEqualTo("id", m.getId());
                	example2.setOrderByClause("index_ desc");
                	List<IndexMenu> list2 = indexMenuMapper.selectByExample(example2);
                	for(IndexMenu m2:list2) {
                		m2.setIndex(m2.getIndex()+1);
                		indexMenuMapper.updateByPrimaryKey(m2);
                	}
        		}
        	}else {
        		return RestResponseBo.fail("已经是第一个了");
        	}
        	
        } catch (Exception e) {
            String msg = "失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }
    
    /**
     * 删除一条评论
     * @param coid
     * @return
     */
    @PostMapping(value = "down")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponseBo<?> down(@RequestParam Long id) {
        try {
        	IndexMenu m = indexMenuMapper.selectByPrimaryKey(id);
        	
        	Example example = new Example(IndexMenu.class);
        	example.createCriteria().andGreaterThanOrEqualTo("index", m.getIndex()).andNotEqualTo("id", m.getId());
        	example.setOrderByClause("index_ desc");
        	List<IndexMenu> list = indexMenuMapper.selectByExample(example);
        	IndexMenu next = null;
        	if(list!=null && list.size()>0) {
        		next = list.get(list.size()-1);
        		if(next.getIndex()>m.getIndex()) {
        			int i = next.getIndex();
        			next.setIndex(m.getIndex());
        			m.setIndex(i);
        			indexMenuMapper.updateByPrimaryKey(next);
        			indexMenuMapper.updateByPrimaryKey(m);
        		}else {
        			//相等了
        			Example example2 = new Example(IndexMenu.class);
                	example2.createCriteria().andLessThanOrEqualTo("index", m.getIndex()).andNotEqualTo("id", m.getId());
                	example2.setOrderByClause("index_ desc");
                	List<IndexMenu> list2 = indexMenuMapper.selectByExample(example2);
                	for(IndexMenu m2:list2) {
                		m2.setIndex(m2.getIndex()-1);
                		indexMenuMapper.updateByPrimaryKey(m2);
                	}
        		}
        	}else {
        		return RestResponseBo.fail("已经是最后一个了");
        	}
        	
        } catch (Exception e) {
            String msg = "失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponseBo.fail(msg);
        }
        return RestResponseBo.ok();
    }

}
